<?php

class Painel_PrestacaoservicoController extends App_Controller_Action
{

    private $_table     = 'PRESTACAO_SERVICO';
    private $_pk        = 'PRS_ID';
    private $_order_col = 'PRS_ID';
    private $_order     = 'DESC';
    private $_sta_col   = 'PRS_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'PRS_FILE'; 
    public  $dir = 'public/upload//';
    public  $db = '';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Painel_Form_Prestacaoservico();        
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        $where = 'WHERE '.$this->_pk . ' > 0';
        
        $dtfiltro = $this->_getParam('dtfiltro', date('d/m/Y'));
        $dscfiltro = $this->_getParam('dscfiltro', '');
        
        if($dtfiltro != '') $where .= ' and B.PRS_DAT = "' .Datetools::dma_amd($dtfiltro).'"';
        if($dscfiltro > '') $where .= ' and C.CLI_NOM like "'. $dscfiltro.'%" ';
        
        $this->view->dtfiltro = $dtfiltro;
        $this->view->dscfiltro = $dscfiltro;
        
        //$query = 'SELECT SQL_CACHE * FROM '.$this->_table.' '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $query = 'SELECT SQL_CACHE B.*,C.CLI_NOM,U.USU_NOM '
                .' FROM '.$this->_table.' B '
                .' INNER JOIN USUARIOS U ON B.USU_ID = U.USU_ID '
                .' LEFT JOIN CLIENTES C ON B.CLI_ID = C.CLI_ID '
                .' '.$where
                .' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_pdr.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_prestacaoservico.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('tools','library');
        
        //$this->view->view = 'view';
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if(1){//$this->form->isValid($formData)) {
                    
                    $id = (int) $formData[$this->_pk];//$this->form->getValue($this->_pk);
                    
                    //$returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                    
                    $data = $formData;//$this->form->getValues();
                    
                    unset($data['img']);
                    unset($data[$this->_file_col]);
                    unset($data['br']);
                    
                    unset($data['SER_ID']);
                    unset($data['SER_QTD']);
                    unset($data['SER_VLR']);
                    unset($data['SER_VLRTOT']);
                    
                    $data['PRS_DAT'] = date('Y-m-d');
                    $data['PRS_HOR'] = date('H:i:s');
                    $data['USU_ID'] = Zend_Auth::getInstance()->getStorage()->read()->USU_ID;
                    $data['PRS_STA'] = 1;
                    
                    $this->db->beginTransaction();
                    if($id == 0){
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId();   
                        //imagem::rename($id,$this->dir,$returnImg['filenew']);
                        
                        foreach($formData['SER_ID'] as $key => $ser_id) {
                            
                            $arr = array(
                                'PRS_ID'    => $id,
                                'SER_ID'    => $ser_id,
                                'PSS_VLR'   => $formData['SER_VLRTOT'][$key],
                                'PSS_QTD'   => $formData['SER_QTD'][$key],
                                'PSS_STA'   => 1,
                            );
                            
                            $this->db->insert('PRESTACAO_SERVICOS', $arr);
                            $pss_id =  $this->db->lastInsertId();
                        
                        }
                    }
                    else $this->db->update($this->_table, $data,$this->_pk.' = ' . $id);
                    
                    //foreach(glob($this->dir.$id.'.*') as $img) imagem::reize($img,$img,'390','150');
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');           
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->db->fetchRow('SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id);
                //$this->form->populate($data);
                $this->view->data = $data;
            
                $query = 'SELECT SQL_CACHE B.*,S.SER_NOM FROM PRESTACAO_SERVICOS B, SERVICO S '
                        .' WHERE B.'.$this->_pk . ' = ' . $id.' AND B.SER_ID = S.SER_ID '
                        .' ORDER BY B.PSS_ID ASC';
                $serv = $this->db->fetchAll($query);
                $this->view->serv = $serv;
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if ((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                $ok = (bool) $this->db->delete('PRESTACAO_SERVICOS',  $this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }    
        }      
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
    }
    
    public function buscaservicoAction(){
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $index = array();
        $result = array();
        
        $q = strtolower($this->_getParam('term'));
        
        $where = 'WHERE SER_STA = 1 and SER_NOM like "'.$q.'%"';
        
        $query = 'SELECT SQL_CACHE * FROM SERVICO '.$where.' ORDER BY SER_NOM ASC';
        $rows = $this->db->fetchAll($query);
        foreach($rows as $res) {
            if(strpos(strtolower($res['SER_NOM']), $q) !== false && array_search($res['SER_NOM'], $index) === false) {
                array_push($result, array('id'=>$res['SER_ID'],'label'=>$res['SER_NOM'],'value'=>$res['SER_NOM'],'preco'=>$res['SER_VLR']));
                $index[] = $res['SER_NOM']; 
            }
            if(count($result) > 20) break;
        }
        echo json_encode($result);
    }
    
}